from django.shortcuts import render
from rest_framework_jwt.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_jwt.settings import api_settings
from rest_framework.generics import GenericAPIView

from .utils import OAuthQQ
from oauth.models import OAuthQQUser
from .exceptions import QQAPIError
from .serializers import OAuthQQUserSerializer
from carts.utils import merge_cart_cookie_to_redis
# https://graph.qq.com/oauth2.0/authoriz?state=%2F&response_type=code&scope=get_user_info&redirect_uri=http%3A%2F%2Fwww.meiduo.site%3A8080%2Foauth_callback.html&client_id=101474184
# url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):
    '''QQ登录的url'''
    def get(self, request):
        '''qq登入的url'''
        next = request.query_params.get('next')
        oauth = OAuthQQ(state=next)
        loginurl = oauth.get_qq_login_url()
        return Response({'login_url': loginurl})

# this.host + '/oauth/qq/user/?code=' + code,
class QQAuthUserView(GenericAPIView):
    '''获得code, 生成Access Token
    Access Token 生成 openid'''
    serializer_class = OAuthQQUserSerializer
    def get(self, request):
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        # 获得access_token
        my_oauth = OAuthQQ()
        try:
            access_token = my_oauth.get_qq_access_token(code)

            # 获得openid
            openid = my_oauth.get_qq_openid(access_token)
        except QQAPIError:
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        #对OauthQQ的数据库查询是否绑定
        try:
            oauth_object = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 用户第一次使用QQ登录
            token = my_oauth.generate_save_user_token(openid)
            return Response({'access_token': token})
        else:
            user = oauth_object.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            response = Response({
                "token": token,
                "username": user.username,
                "user_id": user.id,
            })

            # 在这调用QQ登录时合并购物车
            merge_cart_cookie_to_redis(request=request, response=response, user=user)
            return response

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        response = Response({
            "token": token,
            "username": user.username,
            "user_id": user.id,
        })

        # 在这调用QQ登录时合并购物车
        merge_cart_cookie_to_redis(request=request, response=response, user=user)
        return response



